package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CertificateNoContent;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class AddEmployeePaymentFragment extends EmployeePaymentFragment implements OnClickListener {

  public static final String EXTRA_CODE = "com.isunland.managesystem.ui.EXTRA_CODE";
  private static final int REQUEST_ADDEXTRA = 2;// 附件
  private String paymentCode;// 还款code
  private String paymentNo;// 单据编号
  private BaseVolleyActivity mActivity;
  private CertificateNoContent mNoContent;
  private String receiptsNo; // 单据编号
  private String fee; // 费用摘要
  private String loadSum;// 当前借款合计
  private String repayMoney;// 还款金额
  private String repayPerson;// 还款人
  private String applyPerson;// 申报人
  private String applyDate;// 申报日期
  private String repayDate;// 还款日期
  private String repayType;// 还款方式
  private CurrentUser mCurrentUser;

  @Override public void onCreate(Bundle savedInstanceState) {
    paymentCode = getArguments().getString(EXTRA_CODE);
    mActivity = (BaseVolleyActivity) getActivity();
    mCurrentUser = CurrentUser.newInstance(getActivity());
    // 自动生成id
    id = UUID.randomUUID().toString();
    super.onCreate(savedInstanceState);
  }

  /**
   * 设置 标题
   */
  @Override protected void setTitle() {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar()
        .setTitle(R.string.employeeRepaymentApply);
  }

  /**
   * 初始化数据
   */
  @Override protected void initData() {
    // 还款人
    mLoanPersonRepayment.setText(mCurrentUser.getRealName());
    // 申报人
    mLoanProposerRepayment.setText(mCurrentUser.getRealName());
    // 申报日期
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss ");
    mLoanDateRepayment.setText(format.format(new Date()));
    // 获取单据编码
    getAppayCertificateNo();
    super.initData();
  }

  private void getAppayCertificateNo() {
    // 获取单据编号

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_EMPLOYEE_LOAN_DETAIL);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("certificateCode", paymentCode);
    params.put("userJobNo", mCurrentUser.getJobNumber());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        CertificateNoContent[] array = new Gson().fromJson(arg0, CertificateNoContent[].class);
        mNoContent = array[0];
        paymentNo = mNoContent.getCertificateNo();
        mCertificateNoRepayment.setText(paymentNo);
        mSumBorrowRepayment.setText(mNoContent.getSumBorrow());

        // 开户行
        etpayeeBank.setText(mNoContent.getPayeeBank());
        etpayeeAccname.setText(mNoContent.getPayeeAccname());
        etpayeeAccount.setText(mNoContent.getPayeeAccount());
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * 设置保存提交按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回按钮
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;

      // 响应保存提交按钮
      case R.id.menu_item_save:

        if (TextUtils.isEmpty(mRepayDateRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.payDate, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mPoutAmountRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.payMoney, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mCertificateNoRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
        } else {
          Double payMoney = Double.parseDouble(mPoutAmountRepayment.getText().toString());
          Double borrowMoney = Double.parseDouble(mSumBorrowRepayment.getText().toString());
          double result = borrowMoney - payMoney;
          if (result < 0) {
            Toast.makeText(getActivity(), R.string.errorRepayMoney, Toast.LENGTH_SHORT).show();
          } else if (result >= 0) {
            // //没有附件时
            // vollyPostSave();

            /**
             * 修改添加附件
             */
            // 判断有无附件
            if (TextUtils.isEmpty(mFilePath)) {
              // 附件为空时
              vollyPostSave(SAVE);
            } else {
              // 附件不为空时，先上传附件，再保存数据
              MyUtils.showDialogLoading(getActivity());
              volleyExtra(SAVE);
            }
          }
        }
        break;
      //启动流程
      case R.id.menu_item_submit:

        if (TextUtils.isEmpty(mRepayDateRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.payDate, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mPoutAmountRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.payMoney, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mCertificateNoRepayment.getText().toString())) {
          Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
        } else {
          Double payMoney = Double.parseDouble(mPoutAmountRepayment.getText().toString());
          Double borrowMoney = Double.parseDouble(mSumBorrowRepayment.getText().toString());
          double result = borrowMoney - payMoney;
          if (result < 0) {
            Toast.makeText(getActivity(), R.string.errorRepayMoney, Toast.LENGTH_SHORT).show();
          } else if (result >= 0) {
            /**
             * 修改添加附件
             */
            // 判断有无附件
            if (TextUtils.isEmpty(mFilePath)) {
              // 附件为空时
              //                            vollyPostSave(s);
              showDialog(SAVE_START);
            } else {
              // 附件不为空时，先上传附件，再保存数据
              MyUtils.showDialogLoading(getActivity());
              volleyExtra(SAVE_START);
            }
          }
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog =
        BaseConfirmDialogFragment.newInstance(R.string.cannotEdit, R.string.hintMessage);
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  private void volleyExtra(int requestCode) {

    new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE,
        "r_expense_inexp_main", id, new myUpLoadHandler(requestCode), false);
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {

    private int requestCode;

    public myUpLoadHandler(int requestCode) {
      this.requestCode = requestCode;
    }

    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      // MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          // 上传成功,再上传数据
          selcurFile = result.getMessage().toString();
          selcurFile = selcurFile.replace("\\", "/");
          LogUtil.i("selcurFile==" + selcurFile);
          vollyPostSave(requestCode);
        } else {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      } catch (NotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  private void vollyPostSave(final int requestCode) {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PESONAL_SAVE);

    HashMap<String, String> params = new HashMap<String, String>();

    receiptsNo = mCertificateNoRepayment.getText().toString();// 单据编号
    fee = mExpenseDescRepayment.getText().toString(); // 费用摘要
    loadSum = mSumBorrowRepayment.getText().toString();// 当前借款合计
    repayMoney = mPoutAmountRepayment.getText().toString(); // 还款金额
    repayPerson = mLoanPersonRepayment.getText().toString();// 还款人
    applyPerson = mLoanProposerRepayment.getText().toString(); // 申报人
    applyDate = mLoanDateRepayment.getText().toString(); // 申报日期
    repayDate = mRepayDateRepayment.getText().toString();// 还款日期
    repayType = mRepayTypeRepayment.getText().toString();// 还款方式
    String userId = mCurrentUser.getJobNumber();

    params.put("id", id);
    params.put("certificateNo", receiptsNo);
    params.put("expenseDesc", fee);
    params.put("sumBorrow", loadSum);
    // params.put("poutAmount ", repayMoney );
    params.put("inAmount", repayMoney);

    params.put("draweeName", repayPerson);
    params.put("draweeId", userId);
    params.put("applicantName", applyPerson);
    params.put("applicantId", userId);
    params.put("applyTime", applyDate);
    params.put("occurDate", repayDate);
    params.put("payModeName", repayType);
    params.put("payModeCode", mrepayId);
    params.put("ifReturnLoan", " F");

    // params.put("inAmount" , "0");
    params.put("poutAmount", "0");
    params.put("billNo", "");
    params.put("billAmount", "0");
    params.put("nobillAmount", "0");
    params.put("dataStatus", "new");
    params.put("ifOffBorrow", " F");
    params.put("offBorrow", "0");
    params.put("toutAmount", "0");
    params.put("sumPrebill", "0");
    params.put("replenishAmount", "0");
    params.put("billNoAmount", "0");

    //费用归属
    params.put("fownerkindName", "公司费用");//分类
    params.put("fownerkindCode", "01");//分类code，默认是公司费用
    params.put("appobjectName", mCurrentUser.getMemberName());//对象
    params.put("appobjectId", mCurrentUser.getMemberCode());//对象id,公司会员编码

    // 登记人
    params.put("regStaffName", applyPerson);
    params.put("regStaffId", mCurrentUser.getJobNumber());

    // 新增开户行
    if (!TextUtils.isEmpty(etpayeeBank.getText().toString())) {
      params.put("payeeBank", etpayeeBank.getText().toString());
    } else {
      params.put("payeeBank", "");
    }
    if (!TextUtils.isEmpty(etpayeeAccname.getText().toString())) {
      params.put("payeeAccname", etpayeeAccname.getText().toString());
    } else {
      params.put("payeeAccname", "");
    }
    if (!TextUtils.isEmpty(etpayeeBank.getText().toString())) {
      params.put("payeeAccount", etpayeeAccount.getText().toString());
    } else {
      params.put("payeeAccount", "");
    }

    // 新增附件上传
    params.put("filePath", selcurFile);
    params.put("fileOriginalName", mfileName);
    if (!TextUtils.isEmpty(selcurFile)) {
      params.put("id", id);
    }

    HashMap<String, String> mParams = new HashMap<String, String>();
    mParams.put("json", new JSONObject(params).toString());
    mParams.put("memberCode", mCurrentUser.getMemberCode());
    mParams.put("certificateCode", paymentCode);
    mParams.put("regJobNo", mCurrentUser.getJobNumber());
    mParams.put("type", "mobile");

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mParams, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("arg0==" + arg0);
        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage workProcess = result[0];
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          if (SAVE == requestCode) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else if (SAVE_START == requestCode) {
            //启动流程
            volleyStart();
          }
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  // 启动流程方法
  private void volleyStart() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("isList", "1");
    params.put("id", id);
    params.put("certificateCode", paymentCode);
    LogUtil.i("启动流程params===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        LogUtil.i("启动流程==" + arg0);
        MyUtils.dismissDialog();
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();

          //重新启动时的错误log日志
          LogUtil.e(workProcess.getMessage().toString());

          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.failstartup, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_ADDEXTRA) {
      String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      if (ExtraUpLoadDialogFragment.VALUE_CLEAR.equalsIgnoreCase(result)) {
        clearExtraFile();
      } else {

        mFilePath = result;
        LogUtil.i("mDocPath===" + mFilePath);
        if (mFilePath != null) {

          String fileName = FileUtil.getFileNameByFilePath(mFilePath);
          String[] names = fileName.split("\\.");
          mfileName = names[names.length - 2] + "." + names[names.length - 1];
          mTvExtra.setText(mfileName);
        }
      }
    }

    if (requestCode == SAVE_START) {
      vollyPostSave(SAVE_START);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public void clearExtraFile() {
    mFilePath = "";
    selcurFile = "";
    mTvExtra.setText("");
  }

  // fragment之间传值
  public static AddEmployeePaymentFragment newInstance(String code) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_CODE, code);
    AddEmployeePaymentFragment fragment = new AddEmployeePaymentFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
